package com.quanyan.common.encrypt;

import com.quanyan.common.utils.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author songzj
 * @date 16/4/18-14:31
 */
public class RSAKeyGenerator extends Coder {


    private static Logger logger = LoggerFactory.getLogger(RSAKeyGenerator.class);

    public static void generate() {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_RSA);
            keyPairGenerator.initialize(1024);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            saveKey(encryptBASE64(privateKey.getEncoded()), PRIVATE_KEY);
            saveKey(encryptBASE64(publicKey.getEncoded()), PUBLIC_KEY);
        } catch (Exception e) {
            logger.error(ObjectUtil.getFullStackTraceToString(e));
        }
    }


    private static void saveKey(String key, String fileName) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write(key.getBytes(UTF_8));
        } catch (IOException e) {
            logger.error(ObjectUtil.getFullStackTraceToString(e));
        } finally {

            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
            }
        }
    }
}
